package com.bgds.sys.data.iXCom29d.gateway.impl;

import com.cisdi.data.sdk.gateway.netty.IoSession;
import com.cisdi.data.sdk.gateway.netty.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 保活时间检测，如果超过指定时间，则关闭连接
 * @author cup
 *
 */
public class AliveCheckTask implements Runnable {
	private static final Logger logger = LoggerFactory.getLogger(AliveCheckTask.class);
	
    private SessionFactory sessionFactory;
    private AtomicBoolean shouldRun = null;

    /**
     * 会话允许的保活时间，单位秒
     */
	private int keepAlive;

    private static final double MULTIPLY = 1.5;

	/**
	 * 1秒
	 */

	private static final int SLEEP_INTERNAL = 1000;
    
	public AliveCheckTask(int keepAlive, AtomicBoolean shouldRun, SessionFactory sessionFactory) {
		super();
		this.keepAlive = keepAlive;
		this.shouldRun = shouldRun;
		this.sessionFactory = sessionFactory;
	}
	
	@Override
	public void run() {
		logger.info("启动宝信29d保活超时检测线程");
		
		while (shouldRun != null && shouldRun.get() == true) {
			try {
				long now = System.currentTimeMillis();
				
				List<IoSession> sessions = sessionFactory.getSessions();
				
				for (IoSession ioSession : sessions) {
					BaoXingSession session = (BaoXingSession)ioSession;
					
					// 超出指定倍数保活时间，
					if((now - session.getLastAliveTime()) > (MULTIPLY * keepAlive * 1000)) {
						session.close();
						logger.warn("{} 超出指定倍数{}保活时间{},单位秒，关闭通道", 
								session.gwPrefix(), MULTIPLY, keepAlive);
					}
				}
				
				Thread.sleep(SLEEP_INTERNAL);
			} catch (Exception e) {
				logger.warn(e.getLocalizedMessage(), e);
			}
		}
		
		logger.info("结束宝信29d保活超时检测线程");
	}
}
